import { delMenu, getMenu, listMenu } from '@/api/system/menu'
import DictTag from '@/components/dict-tag/index.vue'
import { formatDate } from '@/utils/common'
import { useDicts } from '@/utils/dict'
import { message } from '@/utils/message'
import { handleTree, useGlobal } from '@pureadmin/utils'
import { ElMessageBox } from 'element-plus'
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import SvgIcon from '@/components/svg-icon/index.vue'

export function useMenu() {
  const { $config } = useGlobal<GlobalPropertiesApi>()

  const data = reactive({
    form: {
      menuId: undefined,
      parentId: 0,
      menuName: undefined,
      icon: undefined,
      menuType: 'M',
      orderNum: undefined,
      isFrame: '1',
      isCache: '1',
      visible: '0',
      status: '0',
    },
    queryParams: {
      menuName: undefined,
      status: undefined,
      osTypes: [0, $config.OSType],
    },
  })
  const { form, queryParams } = toRefs(data)
  const menuId = ref(0)
  const menuOptions = ref([])
  const title = ref('')
  const dataList = ref([])
  const loading = ref(true)
  const isExpandAll = ref(false)
  const refreshTable = ref(true)
  const formDialogVisible = ref(false)
  const { sys_normal_disable } = useDicts('sys_normal_disable')
  const columns: TableColumnList = [
    {
      label: '菜单名称',
      prop: 'menuName',
      align: 'left',
      minWidth: 150,
    },
    {
      label: '图标',
      prop: 'icon',
      align: 'center',
      width: 80,
      cellRenderer: (scope) => {
        return (
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <SvgIcon iconClass={scope.row.icon} />
          </div>
        )
      },
    },
    {
      label: '排序',
      prop: 'orderNum',
      width: 80,
    },
    {
      label: '菜单显示/隐藏',
      prop: 'visible',
      width: 150,
      cellRenderer: ({ row }) => {
        if (row.menuType === 'F') return
        return row.visible === '0' ? (
          <el-tag class="ml-2" type="success">
            显示
          </el-tag>
        ) : (
          <el-tag class="ml-2" type="danger">
            隐藏
          </el-tag>
        )
      },
    },
    {
      label: '路由地址',
      prop: 'path',
      minWidth: 150,
    },
    {
      label: '权限标识',
      prop: 'perms',
      minWidth: 150,
    },
    {
      label: '组件路径',
      prop: 'component',
      minWidth: 150,
    },
    {
      label: '状态',
      prop: 'status',
      width: 80,
      cellRenderer: ({ row }) => {
        return <DictTag options={sys_normal_disable} value={row.status} />
      },
    },
    {
      label: '创建时间',
      width: 180,
      prop: 'createTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 180,
      slot: 'operation',
    },
  ]

  /** 重置新增的表单  */
  function reset() {
    form.value = {
      menuId: undefined,
      parentId: 0,
      menuName: undefined,
      icon: undefined,
      menuType: 'M',
      orderNum: undefined,
      isFrame: '1',
      isCache: '1',
      visible: '0',
      status: '0',
    }
  }

  /** 查询菜单下拉树结构 */
  function getTreeselect() {
    menuOptions.value = []
    const { osTypes } = queryParams.value
    listMenu({ osTypes }).then((response: any) => {
      const menu = { menuId: 0, menuName: '主类目', children: [] }
      menu.children = handleTree(response.data, 'menuId')
      menuOptions.value.push(menu)
    })
  }

  /** 新增按钮操作 */
  function handleAdd(row) {
    reset()
    getTreeselect()
    if (row != null && row.menuId) {
      form.value.parentId = row.menuId
    } else {
      form.value.parentId = 0
    }
    title.value = '添加菜单'
    formDialogVisible.value = true
  }

  /** 展开/折叠操作 */
  function toggleExpandAll() {
    refreshTable.value = false
    isExpandAll.value = !isExpandAll.value
    nextTick(() => {
      refreshTable.value = true
    })
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    getTreeselect()
    menuId.value = row.menuId
    getMenu(menuId.value).then((response: any) => {
      form.value = response.data
      formDialogVisible.value = true
      title.value = '修改菜单'
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    ElMessageBox.confirm('数据一经删除不可恢复，请再次确认！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await delMenu(row.menuId)
      message('删除成功', { type: 'success' })
      onSearch()
    })
  }

  async function onSearch() {
    loading.value = true
    const { data } = await listMenu(queryParams.value)
    const menuList = handleTree(data, 'menuId')
    dataList.value = menuList
    loading.value = false
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    onSearch()
  }

  onMounted(() => {
    onSearch()
  })

  return {
    form,
    title,
    menuId,
    loading,
    columns,
    dataList,
    queryParams,
    isExpandAll,
    menuOptions,
    refreshTable,
    formDialogVisible,
    sys_normal_disable,
    onSearch,
    resetForm,
    handleAdd,
    handleUpdate,
    handleDelete,
    toggleExpandAll,
  }
}
